﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IntoCommon.Util;
using System.Windows.Documents;
using Prism.Commands;
using Prism.Mvvm;
using IntoMes.Models;
using IntoMes.Global;
using System.Windows;

namespace IntoMes.ViewModels
{
    public class StopTimeViewModel : BindableBase
    {
        public ObservableCollection<StationStopTime> Production { get; set; } = new ObservableCollection<StationStopTime>();
        object _locker = new object();

        #region 属性 

        private List<ProductModel> _List;
        /// <summary>
        /// 属性
        /// </summary>
        public List<ProductModel> List
        {
            get { return _List; }
            set
            {
                _List = value;
                RaisePropertyChanged("List");
            }
        }

        private ProductModel _CurModel;
        /// <summary>
        /// 属性
        /// </summary>
        public ProductModel CurModel
        {
            get { return _CurModel; }
            set
            {
                _CurModel = value;
                RaisePropertyChanged("CurModel");
            }
        }
        #endregion 属性


        public StopTimeViewModel()
        {

            List = new List<ProductModel>();
            var lists = GlobalFunc.LoadXmlFile<List<string>>(Paths.recipeCfgFile);
            //GetProductNum(true);
            for (int i = 0; i < lists.Count; i++)
            {
                List.Add(new ProductModel()
                {
                    ModelName = lists[i],
                    ModelValue = i + 1,

                });

            }

        }

        private string querytype;
        private DateTime from = DateTime.Now;
        private DateTime to = DateTime.Now;

        public string QueryType
        {
            get => querytype; set => SetProperty(ref querytype, value);
        }
        public DateTime From
        {
            get => from; set => SetProperty(ref from, value);
        }
        public DateTime To
        {
            get => to; set => SetProperty(ref to, value);
        }

        public void Query()
        {
            Task.Run(() =>
            {
                lock (_locker)
                {
                    try
                    {
                        using (StationStopTimeContext db = new StationStopTimeContext())
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                Production.Clear();
                                List<StationStopTime> query;
                                if (!string.IsNullOrEmpty(QueryType))
                                {
                                    // 获取当前日期和时间
                                    System.DateTime now = System.DateTime.Now;
                                    if (QueryType.Contains("本周"))
                                    {
                                        // 获取今天的日期
                                        System.DateTime today = System.DateTime.Today;
                                        // 计算本周的开始日期（周一）
                                        int daysToMonday = (int)today.DayOfWeek == 0 ? 6 : (int)today.DayOfWeek - 1;
                                        // 计算周一的日期
                                        DateTime startOfWeek = today.AddDays(-daysToMonday);
                                        // 计算本周结束日期的前一天（即不含今天）
                                        var endOfWeek = today.AddHours(23).AddMinutes(59).AddSeconds(59);
                                        query = db.StopTime.Where(o => o.DateTime >= startOfWeek &&
                                                                         o.DateTime <= endOfWeek).ToList();
                                        query= query.GroupBy(p => new { p.StationName, p.ProductMode }).Select(g => new StationStopTime
                                                                         {
                                                                             StationName = g.Key.StationName,
                                                                             ProductMode = g.Key.ProductMode,
                                                                             StopTime = g.Sum(p => p.StopTime)
                                                                         }).ToList();

                                    }
                                    else if (QueryType.Contains("本月"))
                                    {


                                        // 查询本月的数据，但不包含当天的数据
                                        query = db.StopTime.Where(i => i.DateTime.Year == now.Year && i.DateTime.Month == now.Month).ToList();

                                        query= query.GroupBy(p => new { p.StationName, p.ProductMode }).Select(g => new StationStopTime
                                        {
                                            StationName = g.Key.StationName,
                                            ProductMode = g.Key.ProductMode,
                                            StopTime = g.Sum(p => p.StopTime)
                                        }).ToList();
                                    }
                                    else
                                    {
                                        //本年
                                        query = db.StopTime.Where(i => i.DateTime.Year == now.Year).ToList();
                                        query= query.GroupBy(p => new { p.StationName, p.ProductMode }).Select(g => new StationStopTime
                                        {
                                            StationName = g.Key.StationName,
                                            ProductMode = g.Key.ProductMode,
                                            StopTime = g.Sum(p => p.StopTime)
                                        }).ToList();

                                       

                                    }
                                    if (query.Count > 0)
                                    {
                                        if (CurModel != null)
                                        {
                                            query = query.Where(o => o.ProductMode == CurModel.ModelName).ToList();
                                        }
                                        foreach (var msg in query)
                                        {
                                            Production.Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("未查询到对应的数据");
                                        return;
                                    }
                                }
                                else
                                {


                                    From = Convert.ToDateTime(From.ToString("D").ToString());
                                    To = To.Date.AddHours(23).AddMinutes(59).AddSeconds(59);

                                    query = db.StopTime.Where(o => o.DateTime >= From && o.DateTime <= To).ToList();
                                    query= query.GroupBy(p => new { p.StationName, p.ProductMode }).Select(g => new StationStopTime
                                    {
                                        StationName = g.Key.StationName,
                                        ProductMode = g.Key.ProductMode,
                                        StopTime = g.Sum(p => p.StopTime)
                                    }).ToList();

                                    if (CurModel != null)
                                    {
                                        query = query.Where(o => o.ProductMode == CurModel.ModelName).ToList();
                                    }
                                    foreach (var msg in query)
                                    {

                                        Production.Add(msg);
                                    }
                                }
                                db.SaveChanges();
                            });
                        }
                    }
                    catch { }
                }
            });



        }


        private DelegateCommand queryCmd;
      
        
        public DelegateCommand QueryCmd => queryCmd ?? (queryCmd = new DelegateCommand(Query));
      
    }
}
